//
//  UserProfileViewModel.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 13.04.25.
//

import Foundation
class UserProfileViewModel : KoiAccountingBaseViewModel {
    
    @Published var bindWxState = ""
    @Published var logoutState = ""
    @Published var isLoading = false
    
    
    func getUserProfile() {
        KoiAccountingNetApi.standard.userProfile() { result in
            switch result {
            case .success(let success):
                let uid = success?.uid ?? ""
                KoiAccountingUserManager.standard.updateUser(user: success)
                logger.debug("getUserProfile success \(uid) ")
            case .failure(let failure):
                logger.error("getUserProfile fail \(failure) ")
            }
        }
    }
    
    func bindWx() {
        isLoading = true
        WeChatAuthManager.shared.login { result in
            switch result {
            case .success(let success):
                KoiAccountingNetApi.standard.thirdBind(loginParams: success) { result in
                    switch result {
                    case .success(let wxProfile):
                        KoiAccountingUserManager.standard.updateUser(wxProfile: wxProfile)
                        self.isLoading = false
                        self.bindWxState = "success"
                    case .failure(let failure):
                        self.isLoading = false
                        self.bindWxState = failure.netErrorMsg()
                        logger.error("bindWx fail \(failure) ")
                    }
                }
            case .failure(let error):
                self.isLoading = false
                self.bindWxState = error.asAFError?.localizedDescription ?? ""
                logger.error("wechat login fail \(error)")
            }
        }
        
    }
    
    func logout() {
        KoiAccountingNetApi.standard.logout() { result in
            switch result {
            case .success:
                self.isLoading = false
            case .failure(let failure):
                self.isLoading = false
                logger.error("logout fail \(failure) ")
            }
        }
        KoiAccountingUserManager.standard.logout()
        logoutState = "success"
    }
}
